package com.itheima.pay.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.pay.config.WXPayConfigCustom;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Slf4j
@RestController
@RequestMapping("wxpay")
public class WxpayController {


    /**
     * 支付回调通知
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("notify")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            Map<String, String> map = WXPayUtil.xmlToMap(xmlResult);

            // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            String orderId = map.get("out_trade_no");
            String tradeNo = map.get("transaction_id");
            String totalFee = map.get("total_fee");
            String returnCode = map.get("return_code");
            String resultCode = map.get("result_code");

            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }

    /**
     * 下单操作
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("unifiedOrder/{code}")
    public String unifiedOrder(@PathVariable String code) throws Exception {
        WXPayConfigCustom config = new WXPayConfigCustom();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "餐掌柜-餐饮消费");
//        data.put("out_trade_no", "2138091910595900001012");
        data.put("out_trade_no", code);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", "http://s9i997.natappfree.cc/wxpay/notify");
        data.put("trade_type", "NATIVE");  // NATIVE 指定为扫码支付  JSAPI 网站支付
//        data.put("openid", "12");

        try {
            Map<String, String> resp = wxpay.unifiedOrder(data);
            System.out.println("支付结果："+resp);
            return resp.get("code_url");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "OK";
    }


    /**
     * 退款
     * @param code 订单号
     * @param refund_no 退款号
     * @return
     * @throws Exception
     */
    @GetMapping("refunds/{code}/{refund_no}")
    public Map<String, String> refunds(@PathVariable String code, @PathVariable String refund_no) throws Exception {

        WXPayConfigCustom config = new WXPayConfigCustom();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", code);
        data.put("out_refund_no", refund_no);
        data.put("notify_url", "http://s9i997.natappfree.cc/wxpay/notify");
        data.put("refund_desc", "菜品售罄");
        data.put("refund_fee", "1");
        data.put("total_fee", "1");
        data.put("refund_fee_type", "CNY");

        System.out.println("请求参数：" + data);
        Map<String, String> map = wxpay.refund(data);

        return map;
    }

}
